import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../entity/user_entity.dart';
import '../util/dialog_util.dart';
import '../util/dio_util.dart';
import '../util/navigator_util.dart';

import 'login_page.dart';

class RegisterPage extends StatefulWidget {
  final register_color = Color.fromRGBO(244, 244, 244, 10);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "注册",
          style: TextStyle(color: Colors.black),
        ),
        elevation: 0,
        centerTitle: true,
        backgroundColor: RegisterPage().register_color,
        iconTheme: IconThemeData(color: Colors.black),
      ),
      backgroundColor: RegisterPage().register_color,
      body: _Page_Body(),
    );
  }
}

class _Page_Body extends StatefulWidget {
  @override
  _Page_BodyState createState() => _Page_BodyState();
}

class _Page_BodyState extends State<_Page_Body> {
  bool _isCheck = false;
  VoidCallback _onClick;
  UserData _reg_user;
  TextEditingController _nameCon = TextEditingController();
  TextEditingController _phoneCon = TextEditingController();
  TextEditingController _passwordCon = TextEditingController();
  TextEditingController _rePasswordCon = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 70, 0, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          //输入框
          Column(
            children: <Widget>[
              RegisterInputItem(
                "用户名",
                controller: _nameCon,
                inputFormatter: null,
                labelText: "用户名应在11个字符以下",
                isPassword: false,
              ),
              Divider(
                thickness: 2,
                height: 2,
                color: RegisterPage().register_color,
              ),
              RegisterInputItem(
                "手机号",
                controller: _phoneCon,
                inputFormatter: [WhitelistingTextInputFormatter.digitsOnly],
                isPassword: false,
              ),
              Divider(
                thickness: 2,
                height: 2,
                color: RegisterPage().register_color,
              ),
              RegisterInputItem(
                "密码",
                controller: _passwordCon,
                isPassword: true,
              ),
              Divider(
                thickness: 2,
                height: 2,
                color: RegisterPage().register_color,
              ),
              RegisterInputItem(
                "确认密码",
                controller: _rePasswordCon,
                isPassword: true,
              ),
            ],
          ),

          //确认协议
          Padding(
            padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
            child: Container(
              height: 50,
              child: Center(
                child: Row(
                  children: <Widget>[
                    new Checkbox(
                      onChanged: (bool value) {
                        setState(() {
                          _isCheck = value;
                          if (value == true) {
                            _onClick = () {
                              if(_submit()) _sendRegisterReq();
                            };
                          } else {
                            _onClick = null;
                          }
                        });
                      },
                      value: _isCheck,
                    ),
                    Text("同意"),
                    GestureDetector(
                      child: Text(
                        "《用户协议》",
                        style: TextStyle(color: Colors.blue),
                      ),
                      onTap: () {
                        print("点击用户协议");
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),

          //注册按钮
          Padding(
            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            child: ButtonTheme(
              minWidth: 307,
              height: 46,
              child: RaisedButton(
                child: Text(
                  "注册",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: _onClick,
              ),
            ),
          )
        ],
      ),
    );
  }

  bool _submit(){
    String error;
    if(_nameCon.text != ""){
      if(_phoneCon.text != ""){
        if(_passwordCon.text != ""){
          if(_rePasswordCon.text == _passwordCon.text){
            _reg_user = new UserData();
            _reg_user.name = _nameCon.text;
            _reg_user.password = _passwordCon.text;
            _reg_user.phone = _phoneCon.text;
            return true;
          }else{
            error = "两次输入的密码不一致！";
          }
        }else{
          error = "密码不能为空！";
        }
      }else{
        error = "手机号不能为空！";
      }
    }else{
      error = "用户名不能为空！";
    }
    AlertDialogUtil().show(context, "错误", error);
    return false;
  }

  _sendRegisterReq() async{
    var reqBody = {
      "name":_reg_user.name,
      "phone":_reg_user.phone,
      "password":_reg_user.password,
      "address":"无",
      "headImg": "user_head.png"
    };

    var response = await DioUtil().sendPostReq("user/register", reqBody);
    Map resData = response.data;

    UserEntity entity = UserEntity().fromJson(resData);
    AlertDialogUtil().show(context, "注册", entity.massage,onPressed: (){
      if(entity.success){
        NavigatorUtil().push(context, LoginPage(),false);
      }
    });
  }
}

class RegisterInputItem extends StatelessWidget {
  String title;
  bool needDividerOnHead;
  String labelText;
  TextEditingController controller;
  List<TextInputFormatter> inputFormatter;
  bool isPassword = false;

  RegisterInputItem(this.title,
      {this.needDividerOnHead, this.labelText, this.controller,this.inputFormatter,this.isPassword});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 55,
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(50, 0, 0, 0),
            child: Container(
              width: 80,
              child: Text(
                title,
                style: TextStyle(fontSize: 16),
              ),
            ),
          ),
          Container(
            width: 200,
            child: TextField(
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: this.labelText,
                  hintStyle: TextStyle(color: Colors.black38, fontSize: 16),
                  fillColor: Colors.black12,
                  filled: false),
              style: TextStyle(color: Colors.black38, fontSize: 16),
              textAlign: TextAlign.start,
              controller:controller,
              inputFormatters: inputFormatter,
              obscureText: isPassword,
            ),
          ),
        ],
      ),
    );
  }
}
